package hk.ust.comp3111.ustnutrition;

import hk.ust.comp3111.ustnutrition.FeedbackDialog.FeedbackDialogListener;
import hk.ust.comp3111.ustnutrition.UserInfoDialog.UserInfoDialogListener;
import hk.ust.comp3111.ustnutrition.data.DataAccessor;
import hk.ust.comp3111.ustnutrition.data.db.User;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity
		implements FeedbackDialogListener, UserInfoDialogListener
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mPager = (ViewPager)findViewById(R.id.pager);
		mPagerAdapter = new MyPagerAdapter();
		mPager.setAdapter(mPagerAdapter);
		mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int state)
			{
			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels)
			{
			}

			@Override
			public void onPageSelected(int position)
			{
				setTitle(mTabLabels[position]);
				highlightSelectedListItem(position);
			}
		});
		mPager.setCurrentItem(0);
		mPager.setPageMargin((int)MiscUtils.dpToPx(this, 8));
		mPager.setPageMarginDrawable(new ColorDrawable(getResources().getColor(
				R.color.background)));

		mTabLabels = getResources().getStringArray(R.array.tab_labels);
		mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
		mDrawerLayout.setDrawerListener(new MyDrawerListener());
		mDrawerList = (ListView)findViewById(R.id.drawer);
		mDrawerList.setAdapter(ArrayAdapter.createFromResource(this,
				R.array.tab_labels, R.layout.nav_list_item));
		mDrawerList.setOnItemClickListener(new MyDrawerItemClickHandler());

		// The first page is always the one being selected after initialized
		setTitle(mTabLabels[0]);

		mHasDrawerShown = false;

		DataAccessor.Instance.init(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.feedback:
			onFeedbackClick();
			return true;

		case R.id.update_user_info:
			onUpdateUserInfoClick();
			return true;

		case R.id.setup_sync:
			onSetupSyncClick();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onSendFeedback(String feedback)
	{
		if (feedback.isEmpty())
		{
			Toast.makeText(this, R.string.feedback_empty_msg, Toast.LENGTH_LONG)
					.show();
		}
		else
		{
			Intent i = new Intent(Intent.ACTION_SEND);
			i.setType("message/rfc822");
			i.putExtra(Intent.EXTRA_EMAIL,
					new String[]{"comp3111.ust.nutrition@gmail.com"});
			i.putExtra(Intent.EXTRA_SUBJECT, "Feed back of "
					+ getString(R.string.app_name));
			i.putExtra(Intent.EXTRA_TEXT, feedback);
			try
			{
				startActivity(Intent.createChooser(i, "Send feedback through..."));
			}
			catch (Exception e)
			{
				Toast.makeText(this, "There are no email clients installed",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onUpdateUserInfo(User user)
	{
		DataAccessor.Instance.getUser().update(user);

		Intent i = new Intent(this, MainActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
		{
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
		}
		startActivity(i);
		finish();
	}

	private class MyDrawerListener implements DrawerLayout.DrawerListener
	{
		@Override
		public void onDrawerClosed(View drawerView)
		{
			setTitle(mTabLabels[mPager.getCurrentItem()]);
		}

		@Override
		public void onDrawerOpened(View drawerView)
		{
			setTitle(getString(R.string.app_name));
			// Highlight the first item when displaying the first time
			if (!mHasDrawerShown)
			{
				highlightSelectedListItem(mPager.getCurrentItem());
				mHasDrawerShown = true;
			}
		}

		@Override
		public void onDrawerSlide(View drawerView, float slideOffset)
		{
		}

		@Override
		public void onDrawerStateChanged(int newState)
		{
		}
	}

	private class MyDrawerItemClickHandler implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			if (position >= 5 || position < 0)
			{
				position = 0;
			}
			mPager.setCurrentItem(position);

			mDrawerLayout.closeDrawer(mDrawerList);
		}
	}

	private class MyPagerAdapter extends FragmentStatePagerAdapter
	{
		public MyPagerAdapter()
		{
			super(getSupportFragmentManager());
		}

		@Override
		public int getCount()
		{
			return 5;
		}

		@Override
		public Fragment getItem(int position)
		{
			switch (position)
			{
			default:
			case EAT_NOW_POS:
				return new EatNowFragment();

			case FOOD_LIST_POS:
				return new FoodListFragment();

			case MY_HISTORY_POS:
				return new MyHistoryFragment();

			case STAT_POS:
				return new StatisticFragment();

			case MY_PROFILE_POS:
				return new MyProfileFragment();
			}
		}
	}

	private void onFeedbackClick()
	{
		FeedbackDialog d = new FeedbackDialog();
		d.show(getSupportFragmentManager(), "feedback_dialog");
	}

	private void onUpdateUserInfoClick()
	{
		UserInfoDialog d = new UserInfoDialog();
		d.show(getSupportFragmentManager(), "user_info_dialog");
	}

	private void onSetupSyncClick()
	{
		LoginDialog d = new LoginDialog();
		d.show(getSupportFragmentManager(), "login_dialog");
	}

	private void highlightSelectedListItem(int position)
	{
		for (int i = 0; i < mDrawerList.getChildCount(); ++i)
		{
			// Our items are plain TextView
			TextView text = (TextView)mDrawerList.getChildAt(i);
			if (i == position)
			{
				text.setTypeface(Typeface.DEFAULT_BOLD);
				text.setTextColor(getResources().getColorStateList(
						android.R.color.primary_text_light));
			}
			else
			{
				text.setTypeface(Typeface.DEFAULT);
				text.setTextColor(getResources().getColorStateList(
						android.R.color.secondary_text_light));
			}
		}
	}

	private static final int EAT_NOW_POS = 0;
	private static final int FOOD_LIST_POS = 1;
	private static final int MY_HISTORY_POS = 2;
	private static final int STAT_POS = 3;
	private static final int MY_PROFILE_POS = 4;

	private String[] mTabLabels;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;

	private ViewPager mPager;
	private PagerAdapter mPagerAdapter;

	private boolean mHasDrawerShown;
}
